# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

__revision__ = '$Hg: debug.py,v aaebbcd5dd13 2006/09/03 18:30:12 +0200 $'

# system imports
import sys
import os
import traceback

# DDB imports
from ddb.settings import *

# Twisted imports
from twisted.application import service
from twisted.python import log, logfile

application = service.Application('DDB')

def logException(ex, event=None):
    msg = str(ex)
    try:
        result                  = []
        exectype, execvalue, tb = sys.exc_info()
        trace                   = traceback.extract_tb(tb)
        for t in trace:
            file = t[0].split(os.sep)[-1]
            line = t[1]
            call = t[2]
            result.append('%s[%s]: %s' % (file, line, call))
        msg  = 'Exception in %s, %s: %s' % (', '.join(result), exectype, execvalue)
        if '-v' in sys.argv or '-d' in sys.argv:
            traceback.print_exc(sys.stderr)
        del exectype
        del execvalue
        del tb
    finally:
        if event and hasattr(event, 'reply'):
            event.reply(msg)
        log.err(msg)

class InfoLog(log.FileLogObserver):
    def emit(self, logEntryDict):
        for type in ['debug', 'isError', 'transport', 'conference']:
            if logEntryDict.get(type):
                return
        log.FileLogObserver.emit(self, logEntryDict)

class DebugLog(log.FileLogObserver):
    def emit(self, logEntryDict):
        if not logEntryDict.get('debug'):
            return
        log.FileLogObserver.emit(self, logEntryDict)

class ErrorLog(log.FileLogObserver):
    def emit(self, logEntryDict):
        if not logEntryDict.get('isError'):
            return
        log.FileLogObserver.emit(self, logEntryDict)

class ILogService(service.Service):
    def __init__(self, logName, logObserver):
        if not os.path.isdir(LOGDIR):
            try:
                os.mkdir(LOGDIR)
            except OSError:
                print 'Could not create log directory "%s"' % LOGDIR
                sys.exit(1) 
        self.logName     = logName
        self.logObserver = logObserver

    def startService(self):
        print 'Opening log file %s' % self.logName
        self.logFile = logfile.LogFile(
            os.path.basename(self.logName), 
            os.path.dirname(self.logName), 
            rotateLength=LOGSIZE)
        self.logFile.rotate() # rorate upon start time
        self.thelog = self.logObserver(self.logFile)
        self.thelog.start()

    def stopService(self):
        self.thelog.stop()
        self.logFile.close()
        del(self.logFile)

# help
if '-h' in sys.argv:
    print 'DDB version %s' % DDB_VERSION
    print ' (C) Wijnand Modderman <wijnand at tehmaze dot com>'
    print ''
    print './start.py [options]'
    print ''
    print 'options:'
    print ' -D      debug logging'
    print ' -d      daemonize (needs daemon.sh)'
    print ' -h      this help'
    print ' -s      silent, log all to the info file'
    print ' -v      verbose logging to stdout'
    sys.exit(1)
log.startLogging(sys.stdout)
### logging direction
##if '-v' in sys.argv:
##    # hmm just dump it all to stdout :-)
##    log.startLogging(sys.stdout)
##elif '-s' in sys.argv:
##    log.startLogging(open(INFOLOG, 'a'), False)
##else:
##    # start an errorlog file
##    ILogService(ERRORLOG, ErrorLog).setServiceParent(application)
##    ILogService(DEBUGLOG, DebugLog).setServiceParent(application)
##    ILogService(INFOLOG,  InfoLog ).setServiceParent(application)
if '-D' in sys.argv:
    # keep a buffer with scrollable error pages
    log.startKeepingErrors()
if '-d' in sys.argv:
    os.execl(os.path.realpath(
        '%s/../daemon.sh' % os.path.dirname(__file__)))
    os.kill(os.getpid(), 9)

log.msg('Started as: %s' % (' '.join(sys.argv)))

if PIDFILE:
    log.msg('Started with pid %d' % os.getpid())
    pidfd = open(PIDFILE, 'w')
    pidfd.write('%d\n' % os.getpid())
    pidfd.close()

